package com.nd.mobile.study.view;

import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;

import com.nd.mobile.study.R;
import com.nd.mobile.study.common.BaseActivity;
import com.nd.mobile.study.common.constants.BundleConstants;
import com.nd.mobile.study.common.util.ExceptionHandler;
import com.nd.mobile.study.domain.News;
import com.nd.mobile.study.domain.NewsCatalogRoot;
import com.nd.mobile.study.view.adapter.SimpleListAdapter;
import com.nd.mobile.study.view.helper.ToastHelper;
import com.nd.mobile.study.view.widget.Loading;

public class NewsListActivity extends BaseActivity {
	private TabHost							mTabHost;
	private ViewPager						mViewPager;
	private SimpleTabsAdapter				mTabsAdapter;
	private LayoutInflater					mInflater;

	private NewsCatalogRoot[]				mCatalogs;
	private View[]							mListViewContainer;
	private ListView[]						mListViews;
	private NewsListAdapter[]				mListAdapters;

	private AdapterView.OnItemClickListener	mListListener;
	private Intent							mIntent2Detail;

	@Override
	protected void onBaseCreate(Bundle savedInstanceState) {
		setContentView(R.layout.pager_tab);
	}

	@Override
	protected void initViews() {
		super.initHeader();
		mHeaderTitleTv.setText(R.string.app_name);
		mHeaderBtnBack.setVisibility(View.GONE);
		
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup();
	}

	@Override
	protected void setFieldValues() {
		super.setFieldValues();
		mInflater = LayoutInflater.from(this);
		mTabsAdapter = new NewsTabsAdapter(this, mTabHost, mViewPager);
		mLoading = new Loading(this);
		mIntent2Detail = getIntent().setClass(this, NewsDetailActivity.class);
		mListListener = new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				NewsListAdapter adapter = (NewsListAdapter) parent.getAdapter();
				News news = adapter.getData().get(position);
				mIntent2Detail.putExtra(BundleConstants.NEWS, news);
				startActivity(mIntent2Detail);
			}
		};
	}

	@Override
	protected void onAfterCreate(Bundle savedInstanceState) {
		loadRoots();
	}

	private View getTabContentView(int index) {
		if (null == mListViewContainer[index]) {
			View container = mInflater.inflate(R.layout.simple_list, null);
			ListView lv = (ListView) container.findViewById(R.id.common_lv);
			View emptyView = container.findViewById(R.id.common_lv_empty);
			lv.setEmptyView(emptyView);
			lv.setOnItemClickListener(mListListener);

			mListViewContainer[index] = container;
			mListViews[index] = lv;
		}
		return mListViewContainer[index];
	}

	private void loadRoots() {
		mLoading.p();
		new GetCatalogRootTask().execute();
	}

	private class GetCatalogRootTask extends AsyncTask<Void, Void, NewsCatalogRoot[]> {
		private String	errorMsg;

		@Override
		protected NewsCatalogRoot[] doInBackground(Void... params) {
			NewsCatalogRoot[] roots = null;
			try {
				roots = NewsCatalogRoot.loadFromRemote().getBody();
			} catch (Exception e) {
				e.printStackTrace();
				errorMsg = ExceptionHandler.parseExceptionInfo(e);
			}
			return roots;
		}

		@Override
		protected void onPostExecute(NewsCatalogRoot[] result) {
			super.onPostExecute(result);
			if (null != errorMsg) {
				ToastHelper.displayToast(NewsListActivity.this, errorMsg);
			} else {
				handleRoots(result);
			}
		}

		private void handleRoots(NewsCatalogRoot[] result) {
			mListAdapters = new NewsListAdapter[result.length];
			mListViews = new ListView[result.length];
			mListViewContainer = new View[result.length];
			mCatalogs = result;
			// pre-load num
			// mViewPager.setOffscreenPageLimit(result.length);

			String[] label = new String[result.length];
			for (int i = 0; i < label.length; i++) {
				label[i] = result[i].getTitle();
			}
			mTabsAdapter.setTabs(label);
			mLoading.v();
		}
	}

	private void loadList(int index) {
		new GetCatalogListTask().execute(index);
	}

	private class GetCatalogListTask extends AsyncTask<Integer, Void, News[]> {
		private String	errorMsg;
		private int		index;

		@Override
		protected News[] doInBackground(Integer... params) {
			News[] news = null;
			try {
				index = params[0];
				news = mCatalogs[index].getNews().getBody();
			} catch (Exception e) {
				e.printStackTrace();
				errorMsg = ExceptionHandler.parseExceptionInfo(e);
			}
			return news;
		}

		@Override
		protected void onPostExecute(News[] result) {
			super.onPostExecute(result);
			if (null != errorMsg) {
				ToastHelper.displayToast(NewsListActivity.this, errorMsg);
			} else {
				handleNewsList(result);
			}
		}

		private void handleNewsList(News[] result) {
			NewsListAdapter adapter = mListAdapters[index];
			if (null == adapter) {
				adapter = new NewsListAdapter(NewsListActivity.this, result);
				mListAdapters[index] = adapter;
				mListViews[index].setAdapter(adapter);
			} else {
				adapter.setData(result);
			}
			adapter.notifyDataSetChanged();
		}
	}

	private class NewsTabsAdapter extends SimpleTabsAdapter {

		public NewsTabsAdapter(Activity activity, TabHost tabHost, ViewPager pager) {
			super(activity, tabHost, pager);
		}

		@Override
		protected void initPageView(int position) {
			loadList(position);
		}

		@Override
		protected View getPageView(int position) {
			return getTabContentView(position);
		}
	}

//	public static class NewsListAdapter extends BaseAdapter {
//
//		private final class ViewHolder {
//			TextView	title;
//			TextView	date;
//		}
//
//		private LayoutInflater	mInflater;
//		private List<News>		mData;
//
//		public NewsListAdapter(Context context, News[] data) {
//			mInflater = LayoutInflater.from(context);
//			mData = Arrays.asList(data);
//		}
//
//		void setData(News[] data) {
//			mData = Arrays.asList(data);
//		}
//
//		void appendData(News[] data) {
//			mData.addAll(Arrays.asList(data));
//		}
//
//		@Override
//		public int getCount() {
//			return null == mData ? 0 : mData.size();
//		}
//
//		@Override
//		public Object getItem(int position) {
//			return position;
//		}
//
//		@Override
//		public long getItemId(int position) {
//			return position;
//		}
//
//		@Override
//		public View getView(int position, View convertView, ViewGroup parent) {
//			ViewHolder holder;
//			if (null == convertView) {
//				convertView = mInflater.inflate(R.layout.news_list_item, null);
//
//				holder = new ViewHolder();
//				holder.title = (TextView) convertView.findViewById(R.id.news_catalog_title);
//				holder.date = (TextView) convertView.findViewById(R.id.news_catalog_date);
//
//				convertView.setTag(holder);
//			} else {
//				holder = (ViewHolder) convertView.getTag();
//			}
//			holder.title.setText(mData.get(position).getTitle());
//			holder.date.setText(mData.get(position).getDate());
//			return convertView;
//		}
//	}
	
	private class NewsListAdapter extends SimpleListAdapter<News> {

		public NewsListAdapter(Context context, List<News> data) {
			super(context, data);
		}

		public NewsListAdapter(Context context, News[] data) {
			super(context, data);
		}

		private final class ViewHolder {
			TextView	title;
			TextView	date;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (null == convertView) {
				convertView = mInflater.inflate(R.layout.news_list_item, null);

				holder = new ViewHolder();
				holder.title = (TextView) convertView.findViewById(R.id.news_catalog_title);
				holder.date = (TextView) convertView.findViewById(R.id.news_catalog_date);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.title.setText(mData.get(position).getTitle());
			holder.date.setText(mData.get(position).getDate());
			return convertView;
		}
		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean flag = (keyCode == KeyEvent.KEYCODE_BACK);
        if (flag) {
            showExitDialog();
        }
        return flag;
	}
}